package pr.iceworld.fernando.springbatchlearning.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.batch.item.database.AbstractPagingItemReader;
import org.springframework.stereotype.Service;
import pr.iceworld.fernando.springbatchlearning.entity.Users;
import pr.iceworld.fernando.springbatchlearning.repository.UserMapper;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * Created by ferna on 2018/10/17.
 */
@Service
public class ReaderService extends AbstractPagingItemReader<Users> {

    @Resource
    private UserMapper userMapper;

    public ReaderService() {
        super();
        super.setPageSize(3);
    }

    @Override
    protected void doReadPage() {
        if (results == null) {
            results = new CopyOnWriteArrayList<>();
        } else {
            results.clear();
        }
        Page<Users> rowBounds = new Page<>(getPage(), getPageSize());
        results.addAll(userMapper.selectPage(rowBounds, initEntityWrapper()));
        for (Users user: results) {
            System.out.println("Reader Service --->  " + user);
        }

//        Map<String, Object> params = new HashMap<>();
//        params.put("pageSize", getPageSize());
//        params.put("skipRows", getPage() * getPageSize());
//        params.put("age", 20);
//        results.addAll(userMapper.selectAllByParams(params));
//        for (Users user: results) {
//            System.out.println("Reader Service --->  " + user);
//        }
    }

    @Override
    protected void doJumpToPage(int i) {
    }

    private EntityWrapper<Users> initEntityWrapper() {
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        entityWrapper.le("age", 20);
        System.out.println(entityWrapper.getSqlSegment());
        return entityWrapper;
    }
}
